import json
import logging

from config import aiConfig
from instructions.instruction import Instruction
from instructions.enum_types import InstructionType, ActionType
from models import Users
from prompt_template import prompt_tpl
from tools import clean_ai_json
from wechat.reply import ReplyType, Reply

logger = logging.getLogger(__name__)


class RegistryInstruction(Instruction):
    def __init__(self, chatDBHandler=None, query=None):
        super().__init__(chatDBHandler=chatDBHandler, query=query)
        self.prompt = prompt_tpl.REGISTRY_PROMPT
        self.prompt = self.prompt.replace("QUERY", query)
        self.insType: InstructionType = InstructionType.REGISTRY_USER
        logger.info(f"[instruction] Init Instruction query: {query}")

    async def handle_query(self):
        response = await self.query_ollama()
        # response = None
        if not response:
            response = await self.query_other()
            if not response:
                self.chatDBHandler.note = "No AI available for now."
                return Reply(ReplyType.ERROR, "大脑被僵尸吃了,要过会儿才长出来[骷髅]...")
        self.chatDBHandler.ai_answer = response
        if isinstance(response, str) and "无法解析" in response:
            if len(response) > 100:  # 太长，截断
                responses = response.split("\n")[-1]
                for r in responses:
                    if '无法解析' in r:
                        response = r
                        break
            logger.warning("[instruction]用户提供的信息不完整, 无法解析。")
            self.chatDBHandler.add_actions(ActionType.REGISTRY_FAILED)
        else:
            try:
                user_base_info = json.loads(clean_ai_json(response))
                await self.registry(user_base_info)
                response = user_base_info.get("success_info", "用户注册成功！")
                self.chatDBHandler.add_actions(ActionType.REGISTRY_SUCCESS)
                logger.info("[instruction] 用户注册成功.")
            except ValueError:
                self.chatDBHandler.add_actions(ActionType.REGISTRY_FAILED)
                response = "信息不全！注册失败，请说【帮助】，按照格式再发送一次，谢谢"
            except NameError:
                self.chatDBHandler.add_actions(ActionType.REGISTRY_FAILED)
                response = "电话号码不对啊，注册失败了。[委屈]"
        return Reply(ReplyType.TEXT, response)

    async def registry(self, user_base_info: dict):
        """
        把AI解析出来的 name, phone, address 字典作为新的user存入数据库中。
        由于无法肯定AI解析一定正确，需要检测这些数据是否在json对象中。
        :param user_base_info: 一个AI解析后的字典，应该包含key: name, phone, address
        :return:
        """
        if not user_base_info.get("name") or not user_base_info.get("phone") or not user_base_info.get("address"):
            logger.warning("AI 不值得， 解析的信息不全！")
            self.chatDBHandler.add_actions(ActionType.AI_IS_STUPID)
            raise ValueError(f"Missing information {user_base_info}")
        if len(user_base_info.get("phone")) != 11:
            logger.warning("AI 解析的电话号码不正确！")
            self.chatDBHandler.add_actions(ActionType.CHECKSUM_FAILED)
            raise NameError(f"Invalid phone number: {user_base_info.get('phone')}")
        user = Users(name=user_base_info.get("name"),
                     phone=user_base_info.get("phone"),
                     address=user_base_info.get("address"),
                     role='MANAGER',
                     nickname=self.chatDBHandler.msg.from_user_nickname)
        await user.save()
